<template>
  <div class="closing">
    <div style="display: flex">
      <jc-button
        :btn-arr="['reload', 'copy', 'pass', 'option', bomCost('submitVouchers') && 'newy', 'batchFill', 'sub', 'remove']"
        :disab-arr="['close', 'cancel', 'com1', 'com2', 'using', 'freeze', 'chart', 'copy', 'sort']"
        url="tFinVoucher/queryVoucherList"
        @refresh="handleGetUntreated"
        @newly="addCertif"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @submit="submit(1)"
        @noSubmit="submit(2)"
        @del="delCertif"
        @toExcel="handleExport"
        @sort="certifVis"
        @copyDa="copyDa"
      />
      <el-button style="margin-left: 10px" size="mini" type="primary" @click="credentialsTask(2)">{{ $t('market.endVoucher') }}</el-button>
      <el-button style="margin-left: 10px" size="mini" type="primary" @click="credentialsTask(1)">{{ $t('market.carryVouch') }}</el-button>
    </div>
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQuerySonClass"
        />
        <el-button type="primary" class="btn" size="mini" @click="handleQuerySonClass">{{ $t('btn.search') }}</el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        sortable
        table-selection
        :get-summaries="getSummaries"
        show-summary
        @clickRow="listDetail"
        @selectionChange="handleSelectAll"
      >
        <template v-slot:billSlot="col">
          <el-link type="primary" @click="listDetail(col.scope.row)">{{ col.scope.row.fbillNo }}</el-link>
        </template>
        <!--  审核状态  -->
        <template v-slot:tagSlot="col">
          <span v-if="col.scope.row.fdocumentstatus === ''" />
          <el-tag v-else :type="col.scope.row.stateColor">{{ col.scope.row.fdocumentstatus }}</el-tag>
        </template>
        <!--        关闭状态-->
        <template v-slot:btnState="col">
          <el-tag v-if="col.scope.row.closestatus === 'A'" type="primary">{{ $t('market.normal') }}</el-tag>
          <el-tag v-else-if="col.scope.row.closestatus === 'B'" type="danger">{{ $t('btn.closed') }}</el-tag>
        </template>
        <!--        过账状态-->
        <template v-slot:btnStates="col">
          <el-tag v-if="col.scope.row.fpostingstatus === 'A'" type="primary">{{ $t('market.normal') }}</el-tag>
          <el-tag v-else-if="col.scope.row.fpostingstatus === 'B'" type="success">{{ $t('market.postz') }}</el-tag>
        </template>
      </jc-table>
    </div>
    <!--  分页器  -->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        @pagination="handleGetUntreated"
      />
    </div>
    <el-dialog
      v-dialogDrag
      :title="$t('btn.sort')"
      :visible.sync="certifiSort"
      :close-on-click-modal="false"
      close-on-press-escape
      center
    >
      <div style="position: relative;">
        <el-form :model="cateSort" label-width="80px" size="mini">
          <el-form-item :label="$t('market.period')">
            <el-date-picker
              v-model="cateSort.period"
              type="month"
              value-format="yyyy-MM"
              placeholder="选择期间"
            />
            <el-button type="primary" style="margin-left: 10px;" @click="notSort">{{ $t('btn.search') }}</el-button>
            <el-button
              style="position: absolute;right: 0;"
              size="mini"
              type="primary"
              @click="submitCate"
            >{{ $t('market.confirmFinishing') }}</el-button>
          </el-form-item>
          <el-form-item :label="$t('market.sortWay')">
            <el-radio v-model="cateSort.orderType" label="1" @change="notSort">{{ $t('market.createDateSort') }}<!--按创建时间排序--></el-radio>
            <el-radio v-model="cateSort.orderType" label="2" @change="notSort">{{ $t('market.voucherdateSort') }}<!--按凭证日期排序--></el-radio>
          </el-form-item>
        </el-form>
        <div style="margin-bottom: 10px" />
        <jc-table
          :table-header="sortHeader"
          :table-data="sortData"
          table-height="400px"
        >
          <!--  审核状态  -->
          <template v-slot:tagSlot="col">
            <span v-if="col.scope.row.fdocumentstatus === ''" />
            <el-tag v-else :type="col.scope.row.stateColor">{{ col.scope.row.fdocumentstatus }}</el-tag>
          </template>
          <template v-slot:btnSlot="col">
            <el-input v-model.trim.number="col.scope.row.findex" size="mini" />
          </template>
        </jc-table>
      </div>
    </el-dialog>
    <el-dialog
      v-dialogDrag
      title="凭证生产"
      :visible.sync="voucherVisabled"
      :close-on-click-modal="false"
      close-on-press-escape
      center
      width="400px"
    >
      <div>
        <span>{{ $t('market.voucherdate') }}</span>
        <el-date-picker
          v-model="voucheDate"
          type="date"
          value-format="yyyy-MM-dd"
          style="width: 152px;margin-left: 10px;"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="voucherVisabled = false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="voucherCustom">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  auditVouchers, delVouchers, notsubmitVouchers,
  queryVoucherList, submitVouchers, unauditVouchers,
  previewNotSort, previewSort, submitSort, createVoucherByPl, createVoucherByExchangeRate
} from '@/api/financial/voucher'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { notoMxBmina, toMxBmina } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'

export default {
  name: 'VoucherTempList',
  components: {
    search,
    filtration,
    jcButton
  },
  mixins: [searData],
  data() {
    return {
      ftype: 36,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      voucherVisabled: false,
      certifiSort: false,
      voucheDate: '',
      // 表头
      tableData: [], // 销售数据
      tableHeight: '70vh',
      tableHeader: [
        { label: this.$t('market.voucherNum'), type: 'bill', prop: 'fbillNo', width: '130' },
        { label: this.$t('market.voucherdate'), prop: 'voucherdate', width: '100' },
        { label: this.$t('market.documentstatus'), type: 'tag', prop: 'fdocumentstatus', width: '90' },
        { label: this.$t('market.fpostingstatus'), type: 'states', prop: 'fpostingstatus', width: '90' },
        { label: this.$t('market.postinger'), prop: 'postinger', width: '90' },
        { label: this.$t('market.closeState'), type: 'state', prop: 'closestatus', width: '90' },
        { label: this.$t('market.frombillNunber'), prop: 'frombillNo', width: '130' },
        { label: this.$t('market.frombillNoType'), prop: 'ftempName', width: '120' },
        { label: this.$t('market.vwordId'), prop: 'vWordName', width: '80' },
        { label: this.$t('market.vNumber'), prop: 'vNumber', width: '80' },
        { label: this.$t('market.amountIn'), prop: 'amountIn', width: '100' },
        { label: this.$t('market.amountOut'), prop: 'amountOut', width: '100' },
        { label: this.$t('market.digest'), prop: 'description' },
        { label: this.$t('market.dimensionString'), prop: 'dimensionString' },
        { label: this.$t('market.subjectName'), prop: 'subjectName', width: '100' },
        { label: this.$t('market.subjectNum'), prop: 'subjectNumber', width: '100' }
      ],
      tableHeader1: [
        { label: this.$t('market.currency2'), prop: 'fsettlecurr' },
        { label: this.$t('market.currAmount'), prop: 'foriamount' },
        { label: this.$t('market.exchangeType'), prop: 'fexchangetype' },
        { label: this.$t('market.exchangeRate'), prop: 'exchangerate' }
      ],
      cateSort: {
        period: '',
        orderType: ''
      },
      sortData: [],
      sortHeader: [
        { label: this.$t('market.voucherdate'), prop: 'voucherDate' },
        { label: this.$t('market.voucherNum'), prop: 'fbillNo' },
        { label: this.$t('market.documentstatus'), type: 'tag', prop: 'fdocumentstatus' },
        { label: this.$t('market.vwordId'), prop: 'vwordName' },
        { label: this.$t('market.vNumber2'), prop: 'vNumber' },
        { label: this.$t('market.findex'), type: 'btn', prop: 'findex' }
      ]
    }
  },
  created() {
    this.handleGetUntreated()
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '73vh'
  },
  methods: {
    certifVis() {
      this.certifiSort = true
      this.notSort()
    },
    notSort() {
      const api = this.cateSort.orderType ? previewSort : previewNotSort
      api({ ...this.cateSort }).then(res => {
        if (res.code === 0) {
          this.sortData = res.data.list.map(res => {
            return toMxBmina(res)
          })
        }
      })
    },
    // 提交
    submitCate() {
      this.sortData.map(res => {
        return notoMxBmina(res)
      })
      submitSort({ list: this.sortData }).then(res => {
        if (res.code === 0) {
          this.notSort()
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '凭证列表')
        } else {
          queryVoucherList({
            pageSize: 5000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.list.map(item => {
                return toMxBmina(item)
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '凭证列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 获取生产列表数据
    async handleGetUntreated(ev) {
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = { pageNum: this.currentPage, pageSize: this.size, search: this.searCollData.concat(this.details) }
      const RES = await queryVoucherList(DATA)
      if (RES.code === 0) {
        this.tableData = RES.data.list.map(item => {
          return toMxBmina(item)
        })
        this.total = RES.data.total
      } else {
        this.$confirm(RES.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 新增
    addCertif() {
      this.$router.push({ path: '/certificateAdd' })
    },
    // 详情
    listDetail(ev) {
      const id = ev.voucherId
      this.$router.push({ path: `/certificateDetail/${id}` })
    },
    // 全选
    handleSelectAll(val) {
      this.selectFbi = []
      this.voucherId = val[0].voucherId
      val.forEach(res => {
        res.fbillNo && this.selectFbi.push(res.fbillNo)
      })
    },
    // 复制
    copyDa() {
      this.$router.push({
        path: '/certificateAdd',
        query: {
          id: this.voucherId
        }
      })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectFbi }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.selectFbi = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
        this.handleGetUntreated()
      })
    },
    // 审批通过
    async audit(ev) {
      const api = ev === 1 ? auditVouchers : unauditVouchers
      this.toExamineFun(api)
    },
    // 提交反提交
    async submit(ev) {
      const api = ev === 1 ? submitVouchers : notsubmitVouchers
      this.toExamineFun(api)
    },
    // 删除
    delCertif() {
      this.$confirm('该操作将永久删除凭证，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const api = delVouchers
        this.toExamineFun(api)
      })
    },
    // 凭证生成
    credentialsTask(ev) {
      this.apis = ev
      this.voucherVisabled = true
    },
    // 凭证生成
    voucherCustom() {
      const api = this.apis === 1 ? createVoucherByPl : createVoucherByExchangeRate
      api({ voucherdate: this.voucheDate }).then(res => {
        if (res.code === 0) {
          this.voucherVisabled = false
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.tableHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.tableHeader = this.oldTabHeader
      } else {
        this.tableHeader = this.tableHeader1
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.closing {
  @include listBom;

  .header{
    position:relative;
    .header-name{
      width: 100%;
    }
    .btn{
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
